package me.henhaoji.tokenmgr.util;

import java.io.*;
import java.net.*;
import java.util.logging.Logger;

import javax.net.ssl.*;




public class WeixinUtil {

	private static Logger log = Logger.getLogger("weixin");

	/**
	 * 
	 * 发起https请求并获取结�??
	 * 
	 * 
	 * 
	 * @param requestUrl
	 *            请求地址
	 * 
	 * @param requestMethod
	 *            请求方式（GET、POST�??
	 * 
	 * @param outputStr
	 *            提交的数�??
	 * 
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性�??)
	 */

	public static String httpsRequest(String requestUrl,
			String requestMethod, String outputStr) {

	//	JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();

		try {

			// 创建SSLContext对象，并使用我们指定的信任管理器初始�??

			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
					.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式（GET/POST�??
			httpUrlConn.setRequestMethod(requestMethod);
			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();
			// 当有数据�??要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱�??
				
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 将返回的输入流转换成字符�??

			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");

			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}

			bufferedReader.close();
			inputStreamReader.close();

			// 释放资源

			inputStream.close();
			inputStream = null;

			httpUrlConn.disconnect();
			//jsonObject = JSONObject.
				//.fromObject(buffer.toString());

		} catch (ConnectException ce) {

			log.info("error:Weixin server connection timed out.");

		} catch (Exception e) {
			e.printStackTrace();
			log.info("error:https request error:{}");
			
		}

		return buffer.toString();

	}
	public static String request(String requestUrl,
			String requestMethod, String outputStr)
	{
			return request(requestUrl,requestMethod,outputStr,false);
	}
	public static String request(String requestUrl,
			String requestMethod, String outputStr,boolean aysc)
	{
		
		String str=null;
		HttpURLConnection connection;
		try {
			connection = (HttpURLConnection)new URL(requestUrl).openConnection();
			connection.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
//			connection.addRequestProperty("Accept-Encoding","gzip,deflate,sdch");
			connection.addRequestProperty("Accept-Language","zh-CN,zh;q=0.8");
			connection.addRequestProperty("Cache-Control","max-age=0");
			connection.addRequestProperty("Connection","keep-alive");
			//connection.addRequestProperty("Host",host);
			if(aysc)
				connection.setConnectTimeout(2500);
			else
				connection.setConnectTimeout(3500);
			
			connection.setRequestMethod(requestMethod.toUpperCase());
			if(outputStr!=null)
			{	
				connection.setDoOutput(true);
				OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
				out.write(outputStr);
				out.flush();
				out.close();
				/*
			 	connection.getOutputStream().write(outputStr.getBytes("UTF-8"));
			 	connection.getOutputStream().flush();
			 	connection.getOutputStream().close();
			 	*/
			}
			//connection.connect();
			if(connection.getResponseCode()==200)
			{
				str="";
				InputStream inStream=connection.getInputStream();
				BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream,"UTF-8"));
				String lineString="";
				while((lineString=bReader.readLine())!=null){
					str+=lineString+"\n";
				}	
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			//e.printStackTrace();
			if(e instanceof SocketTimeoutException)
			{
				return "";
			}
		}
		return str;
	}
	public static String request2(String requestUrl,
			String requestMethod, String outputStr)
	{
		return request2(requestUrl,requestMethod,outputStr,false);
	}
	public static String request2(final String requestUrl,
			final String requestMethod, final String outputStr,Boolean aysc)
	{
		
		String str="";
		HttpURLConnection connection;
		try {
			connection = (HttpURLConnection)new URL(requestUrl).openConnection();
			connection.addRequestProperty("Accept", "*/*");
			connection.addRequestProperty("Content-Type", "text/xml");
			connection.addRequestProperty("Pragma", "no-cache");
//			connection.addRequestProperty("Accept-Encoding","gzip,deflate,sdch");
			//connection.addRequestProperty("Accept-Language","zh-CN,zh;q=0.8");
			//connection.addRequestProperty("Cache-Control","max-age=0");
			connection.addRequestProperty("Connection","keep-Alive");
			//connection.addRequestProperty("Host",host);
			if(aysc==true)
				connection.setConnectTimeout(1000);
			else if(aysc==false)
				connection.setConnectTimeout(3500);
			else if(aysc==null)
				connection.setConnectTimeout(10000);
			
			connection.setRequestMethod(requestMethod.toUpperCase());
			if(outputStr!=null)
			{	
				connection.setDoOutput(true);
				OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
				out.write(outputStr);
				out.flush();
				out.close();
				/*
			 	connection.getOutputStream().write(outputStr.getBytes("UTF-8"));
			 	connection.getOutputStream().flush();
			 	connection.getOutputStream().close();
			 	*/
			}
			//connection.connect();
			if(connection.getResponseCode()==200)
			{
				System.out.println(200);
				InputStream inStream=connection.getInputStream();
				BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream,"UTF-8"));
				String lineString="";
				while((lineString=bReader.readLine())!=null){
					str+=lineString+"\n";
				}
				
			}
			//connection.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			//e.printStackTrace();
			if(e instanceof SocketTimeoutException)
			{
				
				new Thread(){

					@Override
					public void run() {
						WeixinUtil.request2(requestUrl, requestMethod, outputStr,null);
					}
					
				}.start();
				return null;
			}
		}
		return str;
	}
	
	public static String UrlRequest(String requestUrl,
			String requestMethod, String outputStr)
	{
		
		String str="";
		URLConnection connection;
		try {
			connection = new URL(requestUrl).openConnection();
			connection.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
//			connection.addRequestProperty("Accept-Encoding","gzip,deflate,sdch");
			connection.addRequestProperty("Accept-Language","zh-CN,zh;q=0.8");
			connection.addRequestProperty("Cache-Control","max-age=0");
			connection.addRequestProperty("Connection","keep-alive");
			//connection.addRequestProperty("Host",host);
			connection.setConnectTimeout(4000);
			connection.setReadTimeout(3000);
			
			//connection.setRequestMethod(requestMethod.toUpperCase());
			if(outputStr!=null)
			{	
				connection.setDoOutput(true);
				OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
				out.write(new String(outputStr.getBytes("UTF-8")));	
				out.flush();
				out.close();
				/*
			 	connection.getOutputStream().write(outputStr.getBytes("UTF-8"));
			 	connection.getOutputStream().flush();
			 	connection.getOutputStream().close();
			 	*/
			}
			//connection.connect();
			//if(connection.getResponseCode()==200)
			//{
				InputStream inStream=connection.getInputStream();
				BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream,"UTF-8"));
				String lineString="";
				while((lineString=bReader.readLine())!=null){
					str+=lineString;
			//	}
				
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			//e.printStackTrace();
			if(e instanceof SocketTimeoutException)
			{
				return "";
			}
		}
		return str;
	}

		

}
